import React, { useState } from 'react';
import { 
  Table, 
  Button, 
  Space, 
  Tag, 
  Modal, 
  Form, 
  Input, 
  Switch, 
  Typography,
  Card
} from 'antd';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  EyeOutlined,
  UserOutlined
} from '@ant-design/icons';
import { useThemeStore } from '../../../stores/themeStore';
import { getTheme } from '../../../theme/config';
import { motion } from 'framer-motion';
import { notification } from '../../../components/common'; // 导入自定义通知组件

const { Title, Text } = Typography;

interface User {
  id: number;
  username: string;
  email: string;
  role: string;
  status: 'active' | 'inactive';
  createdAt: string;
  lastLogin: string;
}

const UsersManagement: React.FC = () => {
  const { mode } = useThemeStore();
  const theme = getTheme(mode);
  const [users, setUsers] = useState<User[]>([
    {
      id: 1,
      username: 'admin',
      email: 'admin@example.com',
      role: '超级管理员',
      status: 'active',
      createdAt: '2023-01-15',
      lastLogin: '2023-10-20 14:30'
    },
    {
      id: 2,
      username: 'user1',
      email: 'user1@example.com',
      role: '普通用户',
      status: 'active',
      createdAt: '2023-03-22',
      lastLogin: '2023-10-19 09:15'
    },
    {
      id: 3,
      username: 'user2',
      email: 'user2@example.com',
      role: '普通用户',
      status: 'inactive',
      createdAt: '2023-05-10',
      lastLogin: '2023-10-10 16:45'
    }
  ]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [form] = Form.useForm();

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username'
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email'
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      render: (role: string) => (
        <motion.div
          whileHover={{ scale: 1.05 }}
          whileTap={{ scale: 0.95 }}
        >
          <Tag color={role === '超级管理员' ? 'red' : 'blue'}>{role}</Tag>
        </motion.div>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: 'active' | 'inactive') => (
        <motion.div
          whileHover={{ scale: 1.05 }}
          whileTap={{ scale: 0.95 }}
        >
          <Tag color={status === 'active' ? 'green' : 'red'}>
            {status === 'active' ? '激活' : '停用'}
          </Tag>
        </motion.div>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt'
    },
    {
      title: '最后登录',
      dataIndex: 'lastLogin',
      key: 'lastLogin'
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: User) => (
        <Space size="middle">
          <motion.div whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }}>
            <Button 
              type="primary" 
              icon={<EyeOutlined />} 
              size="small"
              onClick={() => handleViewUser(record)}
              style={{ 
                background: theme.glowColor,
                borderColor: theme.glowColor
              }}
            >
              查看
            </Button>
          </motion.div>
          <motion.div whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }}>
            <Button 
              icon={<EditOutlined />} 
              size="small"
              onClick={() => handleEditUser(record)}
            >
              编辑
            </Button>
          </motion.div>
          <motion.div whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }}>
            <Button 
              icon={<DeleteOutlined />} 
              size="small"
              danger
              onClick={() => handleDeleteUser(record)}
            >
              删除
            </Button>
          </motion.div>
        </Space>
      )
    }
  ];

  const handleViewUser = (user: User) => {
    Modal.info({
      title: '用户详情',
      content: (
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.3 }}
        >
          <Card style={{ 
            background: theme.cardBackground,
            borderColor: theme.cardBorder
          }}>
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.1 }}
            >
              <p><Text strong>用户名:</Text> {user.username}</p>
            </motion.div>
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.2 }}
            >
              <p><Text strong>邮箱:</Text> {user.email}</p>
            </motion.div>
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.3 }}
            >
              <p><Text strong>角色:</Text> {user.role}</p>
            </motion.div>
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.4 }}
            >
              <p><Text strong>状态:</Text> {user.status === 'active' ? '激活' : '停用'}</p>
            </motion.div>
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.5 }}
            >
              <p><Text strong>创建时间:</Text> {user.createdAt}</p>
            </motion.div>
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.6 }}
            >
              <p><Text strong>最后登录:</Text> {user.lastLogin}</p>
            </motion.div>
          </Card>
        </motion.div>
      ),
      okText: '确定',
      icon: <UserOutlined style={{ color: theme.glowColor }} />
    });
  };

  const handleEditUser = (user: User) => {
    setEditingUser(user);
    form.setFieldsValue(user);
    setIsModalVisible(true);
  };

  const handleDeleteUser = (user: User) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除用户 "${user.username}" 吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        setUsers(users.filter(u => u.id !== user.id));
        // 使用自定义通知组件替换 message.success
        notification.success({
          title: '用户删除',
          message: '用户已成功删除'
        });
      },
      icon: <DeleteOutlined style={{ color: '#ff4d4f' }} />
    });
  };

  const handleAddUser = () => {
    setEditingUser(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleModalOk = () => {
    form.validateFields().then(values => {
      if (editingUser) {
        // 更新用户
        setUsers(users.map(user => 
          user.id === editingUser.id ? { ...user, ...values } : user
        ));
        // 使用自定义通知组件替换 message.success
        notification.success({
          title: '用户更新',
          message: '用户已成功更新'
        });
      } else {
        // 添加用户
        const newUser = {
          ...values,
          id: users.length + 1,
          createdAt: new Date().toISOString().split('T')[0],
          lastLogin: '-'
        };
        setUsers([...users, newUser]);
        // 使用自定义通知组件替换 message.success
        notification.success({
          title: '用户添加',
          message: '用户已成功添加'
        });
      }
      setIsModalVisible(false);
    });
  };

  const handleModalCancel = () => {
    setIsModalVisible(false);
  };

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      transition={{ duration: 0.3 }}
    >
      <div style={{ 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'center', 
        marginBottom: 24 
      }}>
        <motion.div
          initial={{ opacity: 0, x: -20 }}
          animate={{ opacity: 1, x: 0 }}
          transition={{ duration: 0.3 }}
        >
          <Title level={3} style={{ color: theme.textPrimary, margin: 0 }}>
            用户管理
          </Title>
        </motion.div>
        <motion.div
          initial={{ opacity: 0, x: 20 }}
          animate={{ opacity: 1, x: 0 }}
          transition={{ duration: 0.3 }}
          whileHover={{ scale: 1.05 }}
          whileTap={{ scale: 0.95 }}
        >
          <Button 
            type="primary" 
            icon={<PlusOutlined />}
            onClick={handleAddUser}
            style={{ 
              background: theme.glowColor,
              borderColor: theme.glowColor,
              boxShadow: theme.cardShadow
            }}
          >
            添加用户
          </Button>
        </motion.div>
      </div>
      
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.3, delay: 0.1 }}
      >
        <Table
          dataSource={users}
          columns={columns}
          rowKey="id"
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true
          }}
          style={{
            background: theme.cardBackground,
            borderRadius: '12px',
            overflow: 'hidden',
            boxShadow: theme.cardShadow
          }}
          scroll={{ x: true }}
        />
      </motion.div>
      
      <Modal
        title={editingUser ? "编辑用户" : "添加用户"}
        visible={isModalVisible}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
        okText="确定"
        cancelText="取消"
        style={{ 
          borderRadius: '12px'
        }}
      >
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.3 }}
        >
          <Form form={form} layout="vertical">
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.1 }}
            >
              <Form.Item
                name="username"
                label="用户名"
                rules={[{ required: true, message: '请输入用户名' }]}
              >
                <Input 
                  placeholder="请输入用户名"
                  style={{ 
                    borderRadius: '8px'
                  }}
                />
              </Form.Item>
            </motion.div>
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.2 }}
            >
              <Form.Item
                name="email"
                label="邮箱"
                rules={[
                  { required: true, message: '请输入邮箱' },
                  { type: 'email', message: '请输入有效的邮箱地址' }
                ]}
              >
                <Input 
                  placeholder="请输入邮箱地址"
                  style={{ 
                    borderRadius: '8px'
                  }}
                />
              </Form.Item>
            </motion.div>
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.3 }}
            >
              <Form.Item
                name="role"
                label="角色"
                rules={[{ required: true, message: '请选择角色' }]}
              >
                <Input 
                  placeholder="请输入角色"
                  style={{ 
                    borderRadius: '8px'
                  }}
                />
              </Form.Item>
            </motion.div>
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3, delay: 0.4 }}
            >
              <Form.Item
                name="status"
                label="状态"
                valuePropName="checked"
              >
                <Switch 
                  checkedChildren="激活" 
                  unCheckedChildren="停用" 
                />
              </Form.Item>
            </motion.div>
          </Form>
        </motion.div>
      </Modal>
    </motion.div>
  );
};

export default UsersManagement;